package utils

import (
	"encoding/json"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"golang.org/x/net/context"
	"net/http"
	"time"
)

type TokenValue struct {
	UserId uint
}

func CreateToken(value TokenValue) string {
	// 生成uuid
	uuid, err := uuid.NewRandom()
	if err != nil {
		panic(err)
	}
	// 存入redis
	expireTime := time.Duration(viper.GetInt64("token.expire")) * time.Second
	v, err := json.Marshal(value)
	if err != nil {
		panic(err)
	}
	err = RDB.Set(context.Background(), uuid.String(), v, expireTime).Err()
	if err != nil {
		panic(err)
	}
	return uuid.String()
}

func GetTokenValue(request *http.Request) (TokenValue, error) {
	token := request.Header.Get("Authorization")
	v, err := RDB.Get(context.Background(), token).Result()
	if err != nil {
		return TokenValue{}, err
	}
	var tokenValue TokenValue
	err = json.Unmarshal([]byte(v), &tokenValue)
	if err != nil {
		return TokenValue{}, err
	}
	return tokenValue, err
}

func GetTokenValueByQuery(request *http.Request) (TokenValue, error) {
	token := request.URL.Query().Get("Authorization")
	v, err := RDB.Get(context.Background(), token).Result()
	if err != nil {
		return TokenValue{}, err
	}
	var tokenValue TokenValue
	err = json.Unmarshal([]byte(v), &tokenValue)
	if err != nil {
		return TokenValue{}, err
	}
	return tokenValue, err
}
